#include<iostream>
#include<algorithm>
#include<vector>						
using namespace std;
struct StringWithDisorder{
	string str;
	int disorder;
	int index;
	StringWithDisorder(string& s, int idx){
		str=s;
		index=idx;
	    disorder = computeDisorder(s);
    }
    //用于排序
    bool operator<(StringWithDisorder& other){
    	if(disorder!=other.disorder );
    	return disorder < other.disorder;
        return index < other.index;  // 无序度相同时按输入顺序排序

	}
	
	private:
		//计算一下无序度
		int computeDisorder(const string& s){
			int n=s.size();
			int count=0;
			for(int i=0;i<n;++i){
				for(int j=i+1;j<n;++j){
					if(s[j]<s[i]){
						count++;
					}
				}
			}
			return count;
		}
};

int main(){
	int n,m;
	cin>>n>>m;
	vector<StringWithDisorder>strings;
	for(int i=0;i<m;++i){
		string s;
		cin>>s;
		strings.emplace_back(s,i);
	}
	sort(strings.begin(),strings.end());
	for(auto it:strings){
		cout<<it.str<<endl;
	}
	return 0; 
}